package priv.dajie.tzzq.bot.c5;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import priv.dajie.tzzq.bot.base.BaseBot;
import priv.dajie.tzzq.bot.c5.exception.C5LoginException;
import priv.dajie.tzzq.common.Tools;
import priv.dajie.tzzq.verifyRec.VerifyRec;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class C5User extends BaseBot implements Runnable{

    private String tradePassword;
    private String c5ID;
    private Logger logger = LogManager.getLogger(this.getClass().getName());
    private Thread thread = null;

    public C5User(String userName, String password, String tradePassword){
        super(userName, password, userName+"c5.cookies");
        this.tradePassword = tradePassword;
    }

    public String getC5ID() {
        return c5ID;
    }

    public String getTradePassword() {
        return tradePassword;
    }

    public void login(){
        login(null);
    }

    public void login(String code){
        if(code == null) {
            loadCookie();
        }
        if(isLogin()) {
            return;
        }
        HttpPost httpPost = new HttpPost("https://www.c5game.com/api/login.json");
        List<NameValuePair> data = new ArrayList<>();
        data.add(new BasicNameValuePair("LoginForm[username]", userName));
        data.add(new BasicNameValuePair("LoginForm[password]", password));
        data.add(new BasicNameValuePair("LoginForm[verify]", code));
        data.add(new BasicNameValuePair("LoginForm[rememberMe]", String.valueOf(1)));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(data));
            String jsonText = open(httpPost);
            JSONObject json = JSON.parseObject(jsonText);
            if(json.getString("message").equals("登录成功")) {
                saveCookies();
            }
            else {
                throw new C5LoginException(json.toString());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public boolean sendVerifySms(){
        HttpPost httpPost = new HttpPost("https://www.c5game.com/api/sms/login.json");
        String jsonText = open(httpPost);
        JSONObject json = JSON.parseObject(jsonText);
        return json.getInteger("status") == 200;
    }

    public void verify(String code){
        HttpPost httpPost = new HttpPost("https://www.c5game.com/api/login/verify.json");
        List<NameValuePair> data = new ArrayList<>();
        data.add(new BasicNameValuePair("type", "2"));
        data.add(new BasicNameValuePair("code", code));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(data));
            String text = open(httpPost);
            JSONObject json = JSON.parseObject(text);
            if(json.getInteger("status")==200) {
                saveCookies();
            }
            else {
                throw new C5LoginException(json.toString());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public boolean isLogin(){
        synchronized (this) {
            if (thread == null) {
                synchronized (this) {
                    thread = new Thread(this);
                    thread.setDaemon(true);
                    thread.start();
                }
            }
        }
        HttpGet httpGet = new HttpGet("https://www.c5game.com/user/login/status.html");
        String html = open(httpGet);
        Document document = Jsoup.parse(html);
        Element userDiv = document.select("div.user-top").first();
        if (userDiv == null) {
            return false;
        }
        Elements as = userDiv.select("a");
        for(Element element : as){
            if(element.attr("href").equals("https://www.c5game.com/user.html")) {
                c5ID = getCookiesByName("C5Login");
                return true;
            }
        }
        return false;
    }

    public boolean isVerify(){
        HttpPost httpPost = new HttpPost("https://www.c5game.com/api/user/checkUser");
        List<NameValuePair> data = new ArrayList<>();
        data.add(new BasicNameValuePair("module", "buy"));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(data));
            String jsonText = open(httpPost);
            JSONObject json = JSON.parseObject(jsonText);
            return json.getInteger("status") != 401;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

    public byte[] getVerifyImgBytes() throws Exception {
        String html = open(new HttpGet("https://www.c5game.com/user/login/ajax.html"));
        Document document = Jsoup.parse(html);
        String imgLink = "https://www.c5game.com"  + document.select("img#loginCaptcha").first().attr("src");
        HttpResponse response = openPro(new HttpGet(imgLink), false);
        InputStream inputStream = response.getEntity().getContent();
        byte[] bytes =  Tools.readInputStream(inputStream);
        inputStream.close();
        return bytes;
    }

    public void getVerifyImg() throws Exception {
        byte[] buffer = getVerifyImgBytes();
        File file = new File("img/c5Verify.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(buffer);
    }


    @Override
    public void run() {
        while(true){
            boolean islogin = isLogin();
            logger.info("c5防掉线执行状态："+islogin);
            if (!islogin){
                login();
            }

            try {
                Thread.sleep(3600*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        C5User c5User = new C5User("17665196730", "g19990214", "199902");
        try {
            c5User.login();
        }catch (C5LoginException e){
            String code = VerifyRec.capreg(c5User.getVerifyImgBytes()).getCode();
            System.out.println(code);
            c5User.login(code);
        }
        try {
            System.out.println("登录验证："+c5User.isLogin());
            System.out.println("短信验证："+c5User.isVerify());
            if(!c5User.isVerify()){
                c5User.sendVerifySms();
                Scanner sc = new Scanner(System.in);
                System.out.println("请输入短信验证码->");
                c5User.verify(sc.nextLine());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
